package org.tacademy.socketclient;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class AndroidSocketClientActivity extends Activity {

	TextView textView01;
	Handler handler;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        textView01 = (TextView)findViewById(R.id.text01);
        Button requestBtn = (Button)findViewById(R.id.requestButton);
        requestBtn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				RequestThread thread = new RequestThread();
				thread.start();
			}
		});
        handler = new Handler();
	}
	
	class RequestThread extends Thread{
		public void run(){
			request();
		}
		public void request(){
			try {
				Socket socket = new Socket("192.168.204.15",5001);
				appendText("client started");
				
				ObjectOutputStream outstream = new ObjectOutputStream(socket.getOutputStream());
				outstream.writeUTF("hello android");
				outstream.flush();
				appendText("data sent");
				
				ObjectInputStream instream = new ObjectInputStream(socket.getInputStream());
				String inString = instream.readUTF();
				appendText("inString from Server"+ inString);
				
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void appendText(String str){
		final String message = str;  
		handler.post(new Runnable() {
			
			public void run() {
				textView01.setText(message);
			}
		});
	}
	
}










